<template>
  <PanerForm :isShowBarDrawer="true" :caption="'编辑服务'">
    <template #body>
      <tabs ref="tabsView" :activeName="'1'">
        <tabs-item title="基本信息" name="1">
          <div class="tab-content">
            <div class="d-row">
              <div class="d-form-group d-form-group-flex d-col-xs-6">
                <div class="d-form-label d-text-right">
                  <label class="label-text">标识</label>
                </div>
                <div class="d-form-el">
                  <input v-model="state.interface" max-length="36" class="d-form-input" type="text" placeholder="必须是英文与数字组合，以英文开头，最大长度36" />
                </div>
                <div class="form-item-selection">
                  <select @change="handleChangeInterTpl" class="d-form-select">
                    <option v-for="item in interTplList" :key="item.id" :value="item.id">{{ item.text }}</option>
                  </select>
                </div>
              </div>
              <div class="d-form-group d-form-group-flex d-col-xs-6">
                <div class="d-form-label d-text-right">
                  <label class="label-text">名称</label>
                </div>
                <div class="d-form-el">
                  <input v-model="state.name" max-length="36" class="d-form-input" type="text" />
                </div>
              </div>
            </div>
            <div class="d-row">
              <div class="d-form-group d-form-group-flex">
                <div class="d-form-label d-text-right">
                  <label class="label-text">接口地址</label>
                </div>
                <div class="d-form-el">
                  <input v-model="state.url" class="d-form-input" type="text" placeholder="如：{host}/user/list/{pageSize}/{page}" />
                </div>
              </div>
              <div class="d-form-group d-form-group-flex">
                <div class="d-form-label d-text-right">
                  <label class="label-text">协议类型</label>
                </div>
                <div class="d-form-el">
                  <select v-model="state.protocol" class="d-form-select">
                    <option v-for="item in protocolList" :key="item.id" :value="item.id">{{ item.text }}</option>
                  </select>
                </div>
              </div>
              <div class="d-form-group d-form-group-flex">
                <div class="d-form-label d-text-right">
                  <label class="label-text">请求方式</label>
                </div>
                <div class="d-form-el">
                  <select v-model="state.method" class="d-form-select">
                    <option v-for="item in methodList" :key="item.id" :value="item.id">{{ item.text }}</option>
                  </select>
                </div>
              </div>
              <div class="d-form-group d-form-group-flex">
                <div class="d-form-label d-text-right">
                  <label class="label-text">功能描述</label>
                </div>
                <div class="d-form-el">
                  <input v-model="state.description" class="d-form-input" type="text" />
                </div>
              </div>
              <div class="d-form-group d-form-group-flex">
                <div class="d-form-label d-text-right">
                  <label class="label-text">详细说明</label>
                </div>
                <div class="d-form-el">
                  <HtmlViewer v-model="state.explain" :mode="STATUS.EDIT" ref="htmlViewer" />
                </div>
              </div>
              <div class="d-form-group d-form-group-flex d-col-xs-6">
                <div class="d-form-label d-text-right">
                  <label class="label-text">状态</label>
                </div>
                <div class="d-form-el">
                  <select v-model="state.state" class="d-form-select">
                    <option v-for="item in statusList" :key="item.id" :value="item.id">{{ item.text }}</option>
                  </select>
                </div>
              </div>
              <div class="d-form-group d-form-group-flex d-col-xs-6">
                <div class="d-form-label d-text-right">
                  <label class="label-text">开发者</label>
                </div>
                <div class="d-form-el">
                  <input v-model="state.developer" class="d-form-input" type="text" />
                </div>
              </div>
              <div class="d-form-group d-form-group-flex d-col-xs-6">
                <div class="d-form-label d-text-right">
                  <label class="label-text">标签</label>
                </div>
                <div class="d-form-el">
                  <input v-model="state.labels" class="d-form-input" type="text" placeholder="分号分隔" />
                </div>
              </div>
              <FormCalendar
                v-if="isEdit"
                v-model="state.updateTime"
                :isEditAble="false"
                :readonly="true"
                format="yyyy-MM-dd HH:mm:ss"
                label="修改时间"
                labelWidth="160px"
                class="d-form-group-flex d-col-xs-6"
              ></FormCalendar>
              <div v-if="false && isEdit" class="d-form-group d-form-group-flex d-col-xs-6">
                <div class="d-form-label d-text-right">
                  <label class="label-text">修改人</label>
                </div>
                <div class="d-form-el">
                  <input v-model="state.updateUser" class="d-form-input" type="text" readonly />
                </div>
              </div>
              <FormCalendar
                v-if="isEdit"
                v-model="state.createTime"
                :isEditAble="false"
                :readonly="true"
                format="yyyy-MM-dd HH:mm:ss"
                label="创建时间"
                labelWidth="160px"
                class="d-form-group-flex d-col-xs-6"
              ></FormCalendar>
              <div v-if="false && isEdit" class="d-form-group d-form-group-flex d-col-xs-6">
                <div class="d-form-label d-text-right">
                  <label class="label-text">创建人</label>
                </div>
                <div class="d-form-el">
                  <input v-model="state.createUser" class="d-form-input" type="text" readonly />
                </div>
              </div>
            </div>
          </div>
        </tabs-item>
        <tabs-item title="请求参数" name="2">
          <div class="tab-content">
            <ParamsView :params="request" />
          </div>
        </tabs-item>
        <tabs-item title="响应内容" name="3">
          <div class="d-section">
            <div class="d-caption-lead">字段</div>
          </div>
          <ParamsView :params="response" />
          <div class="d-section">
            <div class="d-caption-lead">配置</div>
          </div>
          <div class="d-row">
            <div class="d-form-group d-form-group-flex">
              <div class="d-form-label d-text-right">
                <label class="label-text">是否静态响应</label>
              </div>
              <div class="d-form-el">
                <select v-model="state.isStatic" class="d-form-select">
                  <option
                    v-for="item in stock.state.judgeOptions"
                    :key="item.id" :value="item.id">{{ item.text }}</option>
                </select>
              </div>
            </div>
            <div class="d-form-group d-form-group-flex">
              <div class="d-form-label d-text-right">
                <label class="label-text">静态数据</label>
              </div>
              <div class="d-form-el">
                <textarea v-model="state.static" class="d-form-textarea"></textarea>
              </div>
            </div>
          </div>
        </tabs-item>
        <tabs-item title="请求头" name="4">
          <div class="tab-content">
            <HeadersView :headers="state.reqHeaders" />
          </div>
        </tabs-item>
        <tabs-item title="响应头与状态" name="5">
          <div class="tab-content">
            <HeadersView :headers="state.resHeaders" />
          </div>
        </tabs-item>
        <tabs-item title="环境场景" name="6">
          <div class="tab-content"></div>
        </tabs-item>
        <tabs-item title="高级设置" name="7">
          <div class="tab-content">
            <div class="d-row">
              <div class="d-form-group d-form-group-flex">
                <div class="d-form-label d-text-right">
                  <label class="label-text">是否创建服务</label>
                </div>
                <div class="d-form-el">
                  <select v-model="state.isBuildService" class="d-form-select">
                    <option
                      v-for="item in stock.state.judgeOptions"
                      :key="item.id" :value="item.id">{{ item.text }}</option>
                  </select>
                </div>
              </div>
              <div class="d-form-group d-form-group-flex">
                <div class="d-form-label d-text-right">
                  <label class="label-text">代理请求地址</label>
                </div>
                <div class="d-form-el">
                  <input v-model="state.gateway" class="d-form-input" type="text" maxlength="255" placeholder="如：{host}/gateway" />
                </div>
              </div>
              <div class="d-form-group d-form-group-flex">
                <div class="d-form-label d-text-right">
                  <label class="label-text">缓存数据</label>
                </div>
                <div class="d-form-el">
                  <select v-model="state.isCache" class="d-form-select">
                    <option v-for="item in stock.state.judgeOptions" :key="item.id" :value="item.id">{{ item.text }}</option>
                  </select>
                </div>
              </div>
              <div class="d-form-group d-form-group-flex">
                <div class="d-form-label d-text-right">
                  <label class="label-text">缓存类型</label>
                </div>
                <div class="d-form-el">
                  <select v-model="state.cacheType" class="d-form-select">
                    <option v-for="item in stock.state.judgeOptions" :key="item.id" :value="item.id">{{ item.text }}</option>
                  </select>
                </div>
              </div>
              <div class="d-form-group d-form-group-flex">
                <div class="d-form-label d-text-right">
                  <label class="label-text">缓存有效时长(单位:ms)</label>
                </div>
                <div class="d-form-el">
                  <input v-model="state.cacheExpire" class="d-form-input" type="number" maxlength="255" placeholder="输入正整数" />
                </div>
              </div>
              <div class="d-form-group d-form-group-flex">
                <div class="d-form-label d-text-right">
                  <label class="label-text">缓冲请求</label>
                </div>
                <div class="d-form-el">
                  <select v-model="state.isBuffer" class="d-form-select">
                    <option v-for="item in stock.state.judgeOptions" :key="item.id" :value="item.id">{{ item.text }}</option>
                  </select>
                </div>
              </div>
              <div class="d-form-group d-form-group-flex">
                <div class="d-form-label d-text-right">
                  <label class="label-text">缓冲有效时长(单位:ms)</label>
                </div>
                <div class="d-form-el">
                  <input v-model="state.bufferExpire" class="d-form-input" type="number" maxlength="255" placeholder="输入正整数" />
                </div>
              </div>
              <div class="d-form-group d-form-group-flex">
                <div class="d-form-label d-text-right">
                  <label class="label-text">强制响应数据类型</label>
                </div>
                <div class="d-form-el">
                  <select v-model="state.dataType" class="d-form-select">
                    <option v-for="item in stock.state.dataTypeOptions" :key="item.id" :value="item.id">{{ item.text }}</option>
                  </select>
                </div>
              </div>
              <div class="d-form-group d-form-group-flex">
                <div class="d-form-label d-text-right">
                  <label class="label-text">显示进度条</label>
                </div>
                <div class="d-form-el">
                  <select v-model="state.isPreloader" class="d-form-select">
                    <option v-for="item in stock.state.judgeOptions" :key="item.id" :value="item.id">{{ item.text }}</option>
                  </select>
                </div>
              </div>
              <div class="d-form-group d-form-group-flex">
                <div class="d-form-label d-text-right">
                  <label class="label-text">主机</label>
                </div>
                <div class="d-form-el">
                  <input v-model="state.server" class="d-form-input" type="number" />
                </div>
              </div>
              <div class="d-form-group d-form-group-flex">
                <div class="d-form-label d-text-right">
                  <label class="label-text">响应时长(单位:ms)</label>
                </div>
                <div class="d-form-el">
                  <input v-model="state.resTime" class="d-form-input" type="number" minlength="0" maxlength="5" placeholder="输入正整数" />
                </div>
              </div>
              <div class="d-form-group d-form-group-flex">
                <div class="d-form-label d-text-right">
                  <label class="label-text">响应内容处理函数</label>
                </div>
                <div class="d-form-el">
                  <textarea v-model="state.resTransform" class="d-form-textarea"></textarea>
                </div>
              </div>
              <div class="d-form-group d-form-group-flex">
                <div class="d-form-label d-text-right">
                  <label class="label-text">请求XSS注入</label>
                </div>
                <div class="d-form-el">
                  <select v-model="state.isReqXSS" class="d-form-select">
                    <option v-for="item in stock.state.judgeOptions" :key="item.id" :value="item.id">{{ item.text }}</option>
                  </select>
                </div>
              </div>
              <div class="d-form-group d-form-group-flex">
                <div class="d-form-label d-text-right">
                  <label class="label-text">请求XSS注入字段名</label>
                </div>
                <div class="d-form-el">
                  <input v-model="state.reqXSSField" class="d-form-input" placeholder="默认全部字段；多个字段以逗号(,)分隔" />
                </div>
              </div>
              <div class="d-form-group d-form-group-flex">
                <div class="d-form-label d-text-right">
                  <label class="label-text">响应XSS注入</label>
                </div>
                <div class="d-form-el">
                  <select v-model="state.isResXSS" class="d-form-select">
                    <option v-for="item in stock.state.judgeOptions" :key="item.id" :value="item.id">{{ item.text }}</option>
                  </select>
                </div>
              </div>
              <div class="d-form-group d-form-group-flex">
                <div class="d-form-label d-text-right">
                  <label class="label-text">响应XSS注入字段名</label>
                </div>
                <div class="d-form-el">
                  <input v-model="state.resXSSField" class="d-form-input" placeholder="默认全部字段；多个字段以逗号(,)分隔" />
                </div>
              </div>
            </div>
          </div>
        </tabs-item>
      </tabs>
    </template>
    <template #bar-drawer>
      <button @click="handleSubmit" class="d-btn d-btn-primary" type="button">提交</button>
      <button v-if="!isEdit" @click="handleReset" class="d-btn d-btn-default" type="reset">重置</button>
      <a v-d-goback class="d-btn d-btn-default">返回</a>
    </template>
  </PanerForm>
</template>

<script>
import { PanerForm } from '@daelui/vdog/dist/pages'
import { objecter, parser } from '@daelui/dogjs/dist/components'
import { Dialoger, FormCalendar, Tabs, TabsItem } from '@daelui/vdog/dist/components'
import { HtmlViewer } from '@daelui/vdog/dist/viewer'
import { zh as locale } from '@daelui/dogjs/dist/locale'
import { STATUS } from '@daelui/dogjs/dist/constant'
import ParamsView from './structure/params.vue'
import HeadersView from './structure/headers.vue'
import interBis from './structure/business/interface.js'
import interSer from '@/service/action/inter.action.js'
import dictSer from '@/service/action/dictionary.action'
import stock from '@/service/stock/index'

export default {
  components: {
    PanerForm,
    FormCalendar,
    HtmlViewer,
    Tabs,
    TabsItem,
    ParamsView,
    HeadersView
  },

  data () {
    return {
      STATUS,
      isEdit: false, // 是否是编辑模式
      // 表单数据
      state: {
        id: '',
        interface: '',
        url: '{host}/module/controller/action/{pageSize}/{currentPage}',
        protocol: 'http,https',
        method: 'post',
        description: '',
        explain: '',
        status: 1,
        isBuildService: 1,
        developer: '',
        request: {params: []},
        response: {params: []},
        reqHeaders: [],
        resHeaders: [],
        labels: '',
        isReqXSS: 0,
        isResXSS: 0,
        updateTime: '',
        updateUser: '',
        createTime: '',
        createUser: ''
      },
      // 当前列表请求参数数据
      request: {
        children: [{pid: 0, type: 'string', ruleType: 'default', required: 1, isCollapse: false}]
      },
      // 当前列表响应参数数据
      response: {
        children: [{pid: 0, type: 'string', ruleType: 'default', required: 1, isCollapse: false}]
      },
      // 标识模板类型
      interTplList: [
        { id: 'queryItem', text: 'queryItem' },
        { id: 'queryListByPage', text: 'queryListByPage' },
        { id: 'queryListAll', text: 'queryListAll' },
        { id: 'queryTreeAll', text: 'queryTreeAll' },
        { id: 'insert', text: 'insert' },
        { id: 'insertAll', text: 'insertAll' },
        { id: 'update', text: 'update' },
        { id: 'updateAll', text: 'updateAll' },
        { id: 'delete', text: 'delete' },
        { id: 'deleteAll', text: 'deleteAll' }
      ],
      // 协议类型
      protocolList: [],
      // 请求方式列表
      methodList: [],
      // 状态列表
      statusList: [],
      // 存储数据
      stock
    }
  },

  methods: {
    /**
     * @function 加载笔记
    */
    loadItem (id) {
      interSer.queryItem({ id }).then(result => {
        let data = result.data || {}
        data.description = data.description || ''
        this.$refs.htmlViewer.update(data.description)
        // 渲染接口
        this.renderInter(data)
      })
    },
    /**
     * @function 渲染接口
     * @param {Object} inter
    */
    renderInter (inter) {
      // 所属模块
      this.renderModule()
      // 所属模块
      inter = objecter.extend(true, {}, inter)
      inter.request = parser.toObject(inter.request || {})
      inter.request = objecter.isPlainObject(inter.request) ? inter.request : {}
      inter.response = parser.toObject(inter.response || {})
      inter.response = objecter.isPlainObject(inter.response) ? inter.response : {}
      // 请求与响应类型
      // inter.request.type = inter.request.type || 'application/json'
      // inter.response.type = inter.response.type || 'application/json'
      // 请求方式
      inter.method = inter.method || 'post'

      // 当前列表请求参数数据
      this.request = {
        children: []
      }
      // 当前列表响应参数数据
      this.response = {
        children: []
      }
      /* 解包参数 */
      // 请求参数
      let reqParams = inter.request.params || []
      if (reqParams.length < 1) {
        reqParams.push({type: 'string', ruleType: 'default', required: 1})
      }
      inter.request.params = reqParams
      this.request.children = interBis.unPackParams(
        reqParams
      )
      // 请求头
      let reqHeaders = inter.reqHeaders || []
      reqHeaders = parser.toObject(reqHeaders)
      reqHeaders = Array.isArray(reqHeaders) ? reqHeaders : []
      inter.reqHeaders = reqHeaders || []

      // 响应参数
      let resParams = inter.response.params || []
      if (resParams.length < 1) {
        resParams.push({type: 'string', ruleType: 'default', required: 1})
      }
      inter.response.params = resParams
      this.response.children = interBis.unPackParams(
        resParams
      )
      // 响应头
      let resHeaders = inter.resHeaders || []
      resHeaders = parser.toObject(resHeaders)
      resHeaders = Array.isArray(resHeaders) ? resHeaders : []
      inter.resHeaders = resHeaders || []

      this.state = inter
    },
    /**
     * @function 渲染所属模块
    */
    renderModule () {

    },
    // 重置状态
    resetState () {
      this.state = {
        interface: '',
        url: '{host}/module/controller/action/{pageSize}/{currentPage}',
        protocol: 'http,https',
        method: 'post',
        description: '',
        explain: '',
        status: 1,
        isBuildService: 1,
        developer: '',
        order: 1,
        labels: '',
        isCache: '0',
        cacheType: 'memory',
        cacheExpire: '',
        isBuffer: '0',
        bufferExpire: '',
        isPreloader: 0,
        request: {
          params: [{type: 'string', ruleType: 'default', required: 1, valid: 0}]
        },
        response: {
          params: [{type: 'string', ruleType: 'default', required: 1, valid: 0}]
        },
        reqHeaders: [],
        resHeaders: []
      }
    },
    /**
     * @function 修改接口标识模板
    */
    handleChangeInterTpl(e) {
      let value = e.target.value || ''
      this.state.interface = value
    },

    /**
     * @function 提交
    */
    handleSubmit () {
      let defer = null
      let state = objecter.clone(this.state)
      // 包装参数
      state.request.params = interBis.formatParams(
        interBis.packParams(
          objecter.extend(true, [], this.request.children)
        )
      )
      state.response.params = interBis.formatParams(
        interBis.packParams(
          objecter.extend(true, [], this.response.children)
        )
      )
      state.request = parser.stringify(state.request)
      state.response = parser.stringify(state.response)
      // 头数据
      state.reqHeaders = parser.stringify(state.reqHeaders)
      state.resHeaders = parser.stringify(state.resHeaders)
      // 编辑
      if (this.isEdit) {
        defer = interSer.editItem(state)
      } else { // 添加
        defer = interSer.addItem(state)
      }
      defer.then(result => {
        if (result.success) {
          Dialoger.success(locale.action.success)
        } else {
          Dialoger.danger(locale.action.fail)
        }
        // 添加则回到列表页
        if (!this.isEdit) {
          this.$router.push(this.getMicroRoute('/service/inter/list'))
        }
      })
    },
    /**
     * @function 重置
    */
    handleReset () {

    }
  },

  beforeMount () {
    let params = this.$route.params
    // 新建
    if (!params.id) {
      this.isEdit = false
      this.resetState()
      this.renderInter(this.state)
    } else { // 编辑
      this.isEdit = true
      this.loadItem(params.id)
    }
  },

  mounted () {
    // 查询请求协议类型列表
    dictSer.queryProtocolList().then(list => {
      list = Array.isArray(list) ? list : []
      this.protocolList = list
    })
    // 查询请求方式列表
    dictSer.queryMethodList().then(list => {
      list = Array.isArray(list) ? list : []
      this.methodList = list
    })
    // 查询状态列表
    dictSer.queryInterStatusList().then(list => {
      list = Array.isArray(list) ? list : []
      this.statusList = list
    })
  }
}
</script>

<style lang="less" scoped>
.d-form-label {
  width: 160px;
}
.d-form-textarea {
  min-height: 320px;
}
.d-form-group /deep/.ql-container .ql-editor {
  min-height: 200px;
}
.tab-content {
  padding-top: 16px;
}
.form-item-selection {
  margin-left: 8px;
  width: 160px;
  flex-shrink: 0;
}
</style>
